// pages/login/login.js
const request = require('../../utils/request')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    code: '',
    disabled: false,
    phoneLogin: false,
    isLogin: false, //是否已经登录
    recom_code: "",
    pid:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取二维码推广码
    if (options.hasOwnProperty('scene')) {
      if(wx.getStorageSync('token')) {
        wx.switchTab({
          url:'/pages/index/index'
        })
        return
      }
      let scene = decodeURIComponent(options.scene);
      let recom_code = this.getUrlParam(scene, 'recom_code')
      let pid = this.getUrlParam(scene, 'pid')
      console.log(recom_code,pid)
      this.setData({
        recom_code,
        pid
      })
    }
  },

  // 获取url param
  getUrlParam(search, name) {
    // var search = window.location.search.substring(1);
    // if (!search) {
    //   search = window.location.hash.split("?")[1];
    // }
    // console.log(search) //search会取不到在有#hash模式的情况下

    if (search) {
      var obj = JSON.parse(
        '{"' +
        search
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
        '"}'
      );
      return name ? obj[name] : obj;
    }
  },

  onShow() {},
  getUserProfile(e) {
    this.setData({
      disabled: true
    })
    let _this = this
    wx.login({
      success: function (res) {
        if (res.errMsg == 'login:ok') {
          _this.setData({
            code: res.code
          })
        }
      }
    })
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        let userInfo = res
        setTimeout(function () {
          request._get('/api?method=user.wxapplogin1', {
            code: _this.data.code
          }, 'noload').then(tip => {
            let open_id = tip.data
            _this.setData({
              open_id: tip.data,
              disabled: false,
              isLogin: true
            })

            let obj = {
              open_id: tip.data,
              edata: userInfo.encryptedData,
              iv: userInfo.iv
            }
            wx.navigateTo({
              url: '/pages/promotion/promotion?recom_code=' + _this.data.recom_code + "&pid=" + _this.data.pid,
              success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                  data: obj
                })
              }
            })
            return
            request._post('/api?method=user.wxapplogin2', {
              open_id,
              edata: userInfo.encryptedData,
              iv: userInfo.iv
            }, 'noload').then(tips => {
              _this.setData({
                disabled: false,
                isLogin: true
              })
              wx.setStorage({
                key: 'token',
                data: tips.data.token,
                success: function () {
                  getApp().getUserInfo()
                }
              })

            }).catch(function (res) {
              // if (res.data.data == 11027) {
              //   // 手机号授权
              //   _this.setData({
              //     phoneLogin: true
              //   })
              // }
              _this.setData({
                disabled: false
              })
            })

          }).catch(function () {
            _this.setData({
              disabled: false
            })
          })
        }, 100)

      },
      fail() {
        _this.setData({
          disabled: false
        })
      }
    })
  },
  getPhoneNumber(e) {
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      request._post('/api?method=user.wxMobile', {
        open_id: this.data.open_id,
        iv: e.detail.iv,
        edata: e.detail.encryptedData
      }, 'noload').then(tip => {
        this.setData({
          isLogin: true
        })
      })
    }
  },
  // 授权订阅消息
  getMessage(e) {
    wx.requestSubscribeMessage({
      tmplIds: ['Rl6CN2rpWWanao-VnVE760Gdfmru9qrj3LGX6qP_yQY'],
      success(res) {
        if (res['Rl6CN2rpWWanao-VnVE760Gdfmru9qrj3LGX6qP_yQY'] == "accept") {
          wx.switchTab({
            url: '/pages/index/index'
          })
        } else if (res['Rl6CN2rpWWanao-VnVE760Gdfmru9qrj3LGX6qP_yQY'] == "reject") {}
      },
      fail: function (res) {

      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})